﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NBusiness.CodeDom.Services;
using NBusiness.CodeDom;
using NBusiness.ESharp.Compiler;
using NBusiness.CodeDom.Compiler;

namespace NBusiness.ESharp
{
    internal static class Extensions
    {
        public static void FindTemplates(this Entity entity, EntityUsing[] @using, EntityProvider provider, Action<ESharpBuildError> OnBuildError)
        {
            IFrameworkService framework = provider.GetService(typeof(IFrameworkService)) as IFrameworkService;
            EntityTemplate[] templates = framework.GetTemplates();

            foreach (EntityTemplate template in entity.As)
            {
                var foundTemplate = from t in templates
                                    from u in @using
                                    where
                                        t.Type.FullName.ToLower() == template.Name.ToLower() ||
                                        t.Type.FullName.ToLower() == (template.Name + "Template").ToLower() ||
                                        t.Type.FullName.ToLower() == (u.Namespace + "." + template.Name).ToLower() ||
                                        t.Type.FullName.ToLower() == (u.Namespace + "." + template.Name + "template").ToLower()
                                    select t;

                int count = foundTemplate.Count();
                if (count == 0)
                    OnBuildError(new ESharpBuildError(ESharpErrorCode.ES1000, (template as ICompileUnit).Elements[0]));
                else if (count > 1)
                    OnBuildError(new ESharpBuildError(ESharpErrorCode.ES1004, (template as ICompileUnit).Elements[0]));
                else template.Type = foundTemplate.First().Type;
            }
        }
    }
}
